<template>
    <div>
        <el-dialog
            :title="'导入Excel文件，批量翻译'"
            :close-on-click-modal="false"
            width="600px"
            v-dialogDrag
            :visible.sync="isShow"
            @close="closeDialog"
        >
            <el-form size="small" ref="oForm" label-width="90px">
                <el-form-item
                    label=""
                    size="small"
                >
                    <el-upload
                        class="upload-demo"
                        ref="elUpload"
                        drag
                        multiple
                        action="/xxx"
                        :auto-upload="false"
                        :limit="1"
                        :on-change="onChangeFile"
                        :on-exceed="onExceedFile"
                    >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件</div>
                    </el-upload>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submit" size="small" :loading="isLoading">开始导入</el-button>
                    <el-button @click="closeDialog" size="small">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
//导出excel
import ajax from '@/utils/ajax.js'
import jsLoader from '@/utils/jsLoader'
import {libPath} from '@/config/config'

export default {
    name: "importExcel",
    data(){
        return {
            isShow: true,
            isLoading:false,
            aTableData:[],
        }
    },
    methods:{
        toJson(workbook) {
            var result = {};
            workbook.SheetNames.forEach(function(sheetName) {
                var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header:1});
                if(roa.length) {
                    result[sheetName] = roa
                }
            });
            return JSON.stringify(result, 2, 2);
        },
        onExceedFile(file, fileList){
            console.log('err, file, fileList:',file, fileList)
            this.$showError('一次只能删除一个文件，请先删除旧文件')
        },
        onChangeFile(file, fileList){
            console.log('file, fileList:',file, fileList)
            if(!/\.(xls|xlsx)$/.test(file.name)){
                this.$showError('格式不对')
                this.$refs.elUpload.clearFiles()
                return
            }
            jsLoader(`${libPath}xlsx.full.min.js`, () => {
                var f = file.raw;
                var reader = new FileReader();
                reader.onload = (e) => {
                    var data = new Uint8Array(e.target.result);
                    const wb = XLSX.read(data, {type: 'array', codepage: 65001});
                    const aResult = Object.values(JSON.parse(this.toJson(wb)))[0]
                    console.log('aResult:', aResult)
                    const aTitle = aResult.shift()
                    console.log('aTitle:',aTitle)
                    if(!aTitle.includes('ID（请勿修改）') || !aTitle.includes('KEY（请勿修改）') || !aTitle.includes('模块名（请勿修改）')|| !aTitle.includes('中文（Chinese）')|| !aTitle.includes('英文（English）')){
                        this.$showError('excel格式不正确')
                        return
                    }
                    const aTable = []
                    //先过滤空白行，再遍历
                    aResult.filter(item => item.length).forEach(item => {
                        const oTemp = {}
                        aTitle.forEach((item2, index2) => {
                            switch (item2){
                                case 'ID（请勿修改）':
                                    oTemp['id'] = item[index2]
                                    break
                                case 'KEY（请勿修改）':
                                    oTemp['key'] = item[index2].split('.').splice(-1)[0]
                                    break
                                case '模块名（请勿修改）':
                                    oTemp['module'] = item[index2]
                                    break
                                case '中文（Chinese）':
                                    oTemp['zh'] = item[index2]
                                    break
                                case '英文（English）':
                                    oTemp['en'] = item[index2]
                                    break
                            }
                        })
                        //如果英文不为空就添加进去
                        if(oTemp['en'] && oTemp['en'].trim()){
                            aTable.push(oTemp)
                        }
                    })
                    this.aTableData = aTable
                };
                reader.readAsArrayBuffer(f);
            })
        },
        submit(){
            this.$emit('upload', this.aTableData)
        },
        closeDialog(){
            this.$emit('close')
        },
    },
}
</script>

<style lang="scss" scoped>

</style>
